package com.taxi.driver.module.account.identity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.taxi.driver.R;
import com.taxi.driver.common.BaseActivity;
import com.taxi.driver.config.IConstants;
import com.taxi.driver.event.UserEvent;
import com.taxi.driver.module.account.code.CodeActivity;
import com.taxi.driver.module.account.identity.dagger.DaggerIdentifyComponent;
import com.taxi.driver.module.account.identity.dagger.IdentifyModule;
import com.taxi.driver.util.ExChangFilter;
import com.taxi.driver.util.FilterUtils;
import com.taxi.driver.widget.EditTextPlus;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 功能描述：身份证确认页
 * <p>
 * TODO 待修改成MVP模式
 */
public class IdentityActivity extends BaseActivity implements IdentifyContract.View {

    /**
     * 跳转到IdentityActivity
     *
     * @param context
     * @param phone        电话号
     * @param isFirstLogin 是否是首次登录
     */
    public static void actionStart(Context context, String phone, boolean isFirstLogin) {
        Intent intent = new Intent(context, IdentityActivity.class);
        intent.putExtra(IConstants.PHONE, phone);
        intent.putExtra(IConstants.ISFIRSTLOGIN, isFirstLogin);
        context.startActivity(intent);
    }

    @BindView(R.id.img_head_left)
    ImageView mImgHeadLeft;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_notice)
    TextView mTvNotice;
    @BindView(R.id.et_phone)
    EditTextPlus mEtPhone;
    @BindView(R.id.et_id)
    EditTextPlus mEtId;
    @BindView(R.id.tv_next)
    TextView mTvNext;

    String mPhone;
    boolean mIsFirstLogin;

    @Inject
    IdentifyPresenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_identity);
        ButterKnife.bind(this);
        DaggerIdentifyComponent.builder()
                .appComponent(getAppComponent())
                .identifyModule(new IdentifyModule(this))
                .build().inject(this); //依赖注入

        mPhone = getIntent().getStringExtra(IConstants.PHONE);
        mIsFirstLogin = getIntent().getBooleanExtra(IConstants.ISFIRSTLOGIN, false);

        mEtPhone.setText(mPhone); //设置电话号
        Selection.setSelection(mEtPhone.getEditableText(), mEtPhone.getEditableText().length()); //光标移到最后
        if (mPhone.trim().length() == 11) mEtId.requestFocus(); //如果电话号满11位，关闭移到mEtId上
        if (mIsFirstLogin) {
            mTvTitle.setText(R.string.first_login);
            mTvNotice.setText(R.string.first_login_change_pwd_notice);
            mEtPhone.setEnabled(false); //首次登录，不允许修改手机号
        } else {
            mTvTitle.setText(R.string.forget_pwd_title);
            mTvNotice.setText(R.string.forget_pwd_change_notice);
        }

        mEtId.setFilters(new InputFilter[]{new ExChangFilter()});

        mEtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    mEtId.requestFocus(); //光标移到mEtPhone上
                    if (mEtId.getEditableText().length() > 0) {
                        mTvNext.setEnabled(true); //输入满足条件，启用按键
                    }
                } else {
                    mTvNext.setEnabled(false); //输入不满足条件，禁用按键
                }
            }
        });
        mEtId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mEtId.getEditableText().toString().trim().length() > 0 && mEtPhone.getEditableText().toString().trim().length() == 11) {
                    mTvNext.setEnabled(true);
                } else {
                    mTvNext.setEnabled(false);
                }
            }
        });
        mImgHeadLeft.setOnClickListener(v -> {
            closeInput();
            finish(); //关闭界面
        });
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.subscribe();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mPresenter.unsubscribe();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserEvent(UserEvent event) {
        switch (event.type) {
            case UserEvent.RESET_PWD_SUCCESS:
                finish(); //关闭界面
                break;
        }
    }

    @OnClick(R.id.tv_next)
    public void onClick() {
        String phone = mEtPhone.getEditableText().toString().trim();
        String idCard = mEtId.getEditableText().toString().trim();
        if (!FilterUtils.idFilter(idCard)) {
            toast("请输入正确的身份证号");
            return;
        }
        mPresenter.reqVerify(phone, idCard);
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public void verifySuccess(String phone, String idCard) {
        CodeActivity.actionStart(this, phone, mIsFirstLogin, idCard);
    }

    /**
     * 强制关闭输入法
     */
    public void closeInput() {
        InputMethodManager mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (mImm != null)
            mImm.hideSoftInputFromWindow(mEtId.getWindowToken(), 0); //强制隐藏键盘
    }

}
